<?php

namespace App\Http\Controllers\Site\Custom\Provider;

use App\B2BProject\Site\HelperControllerBuildTrait;
use App\B2BProject\Custom\AuthorizationRequest;
use App\B2BProject\Custom\Business\Store;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Auth;

class AuthorizationRequestController extends Controller
{
    use HelperControllerBuildTrait;

    public function getIndex(Request $request)
    {
        if ($request->ajax()) {
            $member = Auth::user();
            if (!$request->pageSize) {
                $request->pageSize = 10;
            }

            $request->query->set('page', $request->query('page', $request->page));
            $request->query->set('pageSize', $request->query('pageSize', $request->pageSize));

            $query = AuthorizationRequest::where('provider_id', $member->id);

            if ($request->input('startTime', false) && $request->input('endTime', false)) {
                $startTime = date('Y-m-d', strtotime($request->startTime));
                $endTime   = date('Y-m-d', strtotime($request->endTime));
                $query     = $query->whereBetween('created_at', [$startTime, $endTime]);
            }

            if ($request->input('name', false)) {
                $query = $query->where('company_name', $request->name);
            }
            $authorization_requests = $query->paginate($request->query('pageSize'));

            $data = [];

            foreach ($authorization_requests as $authorization_request) {
                $data[] = [
                    'id'          => $authorization_request->id,
                    'companyname' => $authorization_request->company_name,
                    'state'       => ['拒绝', '申请中', '已授权', '已终止'][$authorization_request->status],
                    'applydate'   => date("Y-m-d", strtotime($authorization_request->created_at)),
                    'operate'     => $authorization_request->status,
                    'detail_url'  => route('account.member.authorization-request.show', [$authorization_request->id]),
                ];
            }
            $responseText['data']           = $data;
            $responseText['pagingConfData'] = [
                'page'    => $authorization_requests->currentPage(),
                'perpage' => $request->query('pageSize'),
                'total'   => $authorization_requests->total(),
            ];

            return response()->json($responseText);
        }

        \Session::put('purchaser_return', 'account.member.authorization.request.index');

        return view('host/custom/provider/authorization-request/index');
    }

    /**
     * 拒绝
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function refuse(Request $request)
    {
        if ($request->ajax()) {
            $v = Validator::make($request->all(), [
                'id' => 'required|numeric|exists:authorization_requests,id',
            ]);

            if ($v->fails()) {
                return $this->getIndex($request);
            }

            $authorization = Auth::user()->providerAuthorizationRequests()->where($request->id)->firstOrFail();

            if ($authorization->status == 2) {
                return response('Forbidden!', 403);
            }

            $authorization->status = 0;
            $authorization->save();
        }

        return $this->getIndex($request);
    }

    /**
     * 同意授权
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function agree(Request $request)
    {
        if ($request->ajax()) {
            $v = Validator::make($request->all(), [
                'id'        => 'required|numeric|exists:authorization_requests,id',
                'startTime' => 'required|date',
                'endTime'   => 'required|date',
            ]);

            if ($v->fails()) {
                return $this->getIndex($request);
            }

            $authorization = Auth::user()->providerAuthorizationRequests()->whereId($request->id)->firstOrFail();

            if ($authorization->status == 2 || $authorization->status == 0) {
                return response('Forbidden!', 403);
            }

            $authorization->authorize_start = date('Y-m-d', strtotime($request->startTime));
            $authorization->authorize_stop  = date('Y-m-d', strtotime($request->endTime));
            $authorization->process_status  = 1; // 授权过程状态为：合作中
            $authorization->status          = 2; // 申请状态为：同意

            $authorization->save();
        }

        return $this->getIndex($request);
    }

    public function show($id)
    {
        $authorization = AuthorizationRequest::findOrFail($id);

        return view('host/custom/provider/authorization-request/show',
            ['authorization' => $authorization, 'return' => session('purchaser_return')]);
    }
}
